package cn.edu.hhtc.stsystem.security.userdetails;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import cn.edu.hhtc.stsystem.security.domain.SysAuthorities;
import cn.edu.hhtc.stsystem.security.domain.SysUsers;
import cn.edu.hhtc.stsystem.security.service.UserService;
import cn.edu.hhtc.stsystem.security.utils.ThreadLocalRoleId;

/**
 * 
 * @author linyueqin
 * 
 */
public class StsUserDetailsService implements UserDetailsService {

	@Autowired
	private UserService userService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

		List<GrantedAuthority> authsList = new ArrayList<GrantedAuthority>();
		SysUsers user = null;
		try {
			user = this.userService.getUserByLoginName(username);
			if (user == null) {
				throw new UsernameNotFoundException("用户不存在");
			}
			List<SysAuthorities> authorityList = this.userService.getAuthorities(user.getId(),
					ThreadLocalRoleId.getRoleId());
			if (CollectionUtils.isNotEmpty(authorityList)) {
				for (SysAuthorities authority : authorityList) {
					authsList.add(new GrantedAuthorityImpl(authority.getName()));
				}
			}
		} catch (Exception e) {
			throw new UsernameNotFoundException("用户不存在");
		}

		User userdetail = new User(username, user.getPassword(), true, true, true, true, authsList);

		return userdetail;
	}
}
